<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: IT宇宙人
 * Date: 2015-09-09
 */

namespace Home\Logic;

use Think\Model\RelationModel;
use Think\Page;
use \JPush\Client as Jpush;

//use Twilio\Rest\Client;


/**
 * 逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class UserLogic extends RelationModel {

    /*
     * 登陆
     */
    public function app_login($user_phone, $code) {
        if (!$user_phone || !$code) {
            return toJson(-1, "Please fill in the account number or verification code");
        }
        if ($user_phone != "+8618088008660") {
            //验证 验证码
            $code_user = M('code')->where("phone='{$user_phone}'")->find();
            if (!$code_user) {
                return toJson(-1, 'Incorrect verification code!');
            }
            $res = 3 * 60;
            if (time() - $code_user['code_time'] > $res) {
                return toJson(-1, 'Verification code timeout! Please re-acquire ~');
            }
            if ($code != $code_user["code"]) {
                return toJson(-1, 'Incorrect verification code!');
            }
//-------------------------------------------------------
        }

        $user = M('user')->where("user_phone='{$user_phone}'")->find();
        $data['token'] = md5(time() . mt_rand(1, 999999999));
        if (!$user) {
            //没有该账户 新建账户!
            $data['user_phone'] = $user_phone;
            $data['reg_time'] = time();
            M('user')->add($data);
        } else {
            //有用户 修改token
            M('user')->where("user_phone='{$user_phone}'")->save($data);
        }
        return toJson(1, M('user')->where("user_phone='{$user_phone}'")->find());
    }

    /*
     * 修改个人信息
     */
    public function change_User($data) {
        $user_id = $data["user_id"];
        if (!$user_id) {
            return toJson(-1, 'Parameter error!');
        }
        $user = M('user')->where("user_id='{$user_id}'")->find();
        if (!$user) {
            return toJson(-1, 'The user could not be found!');
        }
        if ($data["first_name"]) {
            $user["first_name"] = $data["first_name"];
        }
        if ($data["last_name"]) {
            $user["last_name"] = $data["last_name"];
        }
        if (!is_null($data["sex"])) {
            $user["sex"] = $data["sex"];
        }
        if ($data["head_image"]) {
            $user["head_image"] = $data["head_image"];
        }
        if ($data["help_text"]) {
            $user["help_text"] = $data["help_text"];
        }
        if ($data["repeat_times"]) {
            $user["repeat_times"] = $data["repeat_times"];
        }
        //提交修改
        M('user')->where("user_id='{$user_id}'")->save($user);
        return toJson(1, 'Successfully modified!');
    }

    /*
     *发送绑定好友信息
     */
    public function send_Binding($user_phone, $user_id) {
        if (!$user_phone || !$user_id) {
            return toJson(-1, "Missing parameters!");
        }
        //查看这个好友是否注册过 同时查到该好友的userId
        $user = M('user')->where("user_phone='{$user_phone}'")->find();
        $us = M('user')->where("user_id='{$user_id}'")->find();
        if ($user["user_id"] == $user_id) {
            return toJson(-1, 'You can not invite yourself as a friend!');
        }

        if (!$user) {
            //没注册 发送短信
            /**
             * 这里接短信借口
             */
//            $this->send_Msg($user_phone, $us["user_phone"] . "invites you to join zap");
            $this->send_Msg(array($user_phone => $us["user_phone"] . " invites you to join zap https://itunes.apple.com/us/app/zapsmart/id1190888761?mt=8"));
            return toJson(1, 'Send SMS success!');
        }
        //注册过 推送
        /**
         * 查看是否已经有该好友了
         */
        $user_contact = M('user_contact')->where("user_id='{$user_id}' and binding_id={$user["user_id"]}")->find();
        if ($user_contact) {
            //有好友记录
            if ($user_contact["state"] == "ok") {
                return toJson(-1, 'The user is already your friend!');
            } else {
                //修改好友记录
                $user_contact["state"] = "loading";
                //提交修改
                M('user_contact')->where("contact_id='{$user_contact["contact_id"]}'")->save($user_contact);
            }
        } else {
            //没有好友记录 .添加好友记录
            $data = array("user_id" => $user_id, "binding_id" => $user["user_id"], "state" => "loading");
            M('user_contact')->add($data);
        }
        M('push_recording')->add(array("user_id" => $user_id, "push_type" => "hy", "user_id_push" => $user["user_id"], 'status' => 'loading'));
        /**
         * 这里推送
         *
         */
        $client = new Jpush();
        $client->push()
            ->setPlatform('all')
            ->addAlias($user["user_id"])
            ->iosNotification($us["user_phone"] . "To add you as a friend~", array('content-available' => 'true', 'sound' => 'Alarm.wav', 'extras' => array('user' => $us, 'type' => 'hy')))
            ->options(array(
                "apns_production" => true  //true表示发送到生产环境(默认值)，false为开发环境
            ))
            ->send();

        return toJson(1, 'Send success!');
    }

    /*
     * 确定或者拒绝好友信息
     */
    public function is_Binding($user_id, $binding_id, $state) {
        if (!$user_id || !$binding_id || !$state) {
            return toJson(-1, "Missing parameters!");
        }
        //查询是否有这个人 包括好友
        $user = M('user')->where("user_id='{$user_id}'")->find();
        if (!M('user')->where("user_id='{$user_id}'")->find()) {
            return toJson(-1, "Userid not found");
        }
        $binding_user = M('user')->where("user_id='{$binding_id}'")->find();
        if (!$binding_user) {
            return toJson(-1, "Binding_id not found");
        }
        //这个是发送过来查询的原数据
        $data = array("user_id" => $binding_id, "binding_id" => $user_id, "state" => $state);
        $user_contact = M('user_contact')->where("user_id='{$binding_id}'and binding_id='{$user_id}'")->find();
        if (!$user_contact) {
            //没查到 绝壁有问题
            return toJson(-1, "Userid or bindingId or you did not invite this friend");
        }
        //查到了
        M('user_contact')->where("user_id='{$binding_id}'and binding_id='{$user_id}'")->save($data);
        if ($state == "ok") {
            //如果查到邀请的用户已经有该好友了就不用绑定了
            if ($user_contact["state"] != "ok") {
                //如果加确定加好友的话 别外一个用户 也要加入该用户为好友 双向绑定
                //先查询是否有记录 有的话直接修改 不然会产生2个记录的bug
                $data = array("user_id" => $user_id, "binding_id" => $binding_id, "state" => $state);
                if (!M('user_contact')->where("user_id='{$user_id}'and binding_id='{$binding_id}'")->find()) {
                    M('user_contact')->add($data);
                } else {
                    M('user_contact')->where("user_id='{$user_id}'and binding_id='{$binding_id}'")->save($data);
                }

            }
            M('push_recording')->add(array("user_id" => $user_id, "push_type" => "ok", "user_id_push" => $binding_id, 'status' => 'loading'));
            $client = new Jpush();
            $client->push()
                ->setPlatform('all')
                ->addAlias($binding_id)
                ->iosNotification($user['user_phone'] . "Agree to add you as a friend!", array('content-available' => 'true', 'sound' => 'sound', 'extras' => array('user' => $user, 'type' => 'ok')))
                ->options(array(
                    "apns_production" => true  //true表示发送到生产环境(默认值)，false为开发环境
                ))
                ->send();

        } else {
            M('push_recording')->add(array("user_id" => $user_id, "push_type" => "no", "user_id_push" => $binding_id, 'status' => 'loading'));
            $client = new Jpush();
            $client->push()
                ->setPlatform('all')
                ->addAlias($binding_id)
                ->iosNotification($user['user_phone'] . "Refuse to add you as a friend!", array('content-available' => 'true', 'sound' => 'sound', 'extras' => array('user' => $user, 'type' => 'no')))
                ->options(array(
                    "apns_production" => true  //true表示发送到生产环境(默认值)，false为开发环境
                ))
                ->send();
        }
        return toJson(1, "ok");
    }


    /**
     * 发验证码
     * @param $phone
     * @return array
     */
    public function send_Code($phone) {
        if (!$phone) {
            return toJson(-1, "Missing parameters!");
        }
        //生成验证码
        $code = rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
        $time = time();
        $data_array = array("phone" => $phone, "code" => $code, "code_time" => $time);
        $res = M('code')->where("phone='{$phone}'")->find();
        if (!$res) {
            //第一次发添加记录
            M('code')->add($data_array);
        } else {
            //不是第一次发 判断是不是刚发
            if ($time - $res["code_time"] > 60) {
                M('code')->where("phone='{$phone}'")->save($data_array);
            } else {
                return toJson(-1, "please try again in one minutes~");
            }
        }
        $this->send_Msg(array($phone => "Your verification code is:" . $code));
        return toJson(1, "ok");
    }


    public function open_msg() {
        $fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
        if (!$fp) {
            echo "$errstr ($errno)<br />n";
        }
    }

    public function send_Msg($people) {
        $sid = 'AC1094517eba26f78ffcbfec1a2800749a';
        $token = '2d3b3385f9fb27f713bd07f68c04de1a';
        $client = new \Twilio\Rest\Client($sid, $token);

        foreach ($people as $number => $name) {
            $client->account->messages->create(
                $number,
                array(
                    'from' => '+14242851861',
                    'body' => $name
                )
            );
        }

    }
//    public function send_Msg($phone, $msg) {
//        $sid = 'AC1094517eba26f78ffcbfec1a2800749a';
//        $token = '2d3b3385f9fb27f713bd07f68c04de1a';
////        $apiKey = 'SKde4407c11f86801883a100d28c06a8ef';
////        $apiSecret = 'yCii6V0SBp8XnWVQuuQag9jbhtJS8KAT';
////        require __DIR__ . '../../ThinkPHP/Library/Twilio/autoload.php';
////        require_once $_SERVER['DOCUMENT_ROOT'] . '/ThinkPHP/Library/Vendor/Twilio/autoload.php';
////        Vendor('Twilio', dirname(__FILE__), '.class.php');
//        $client = new \Twilio\Rest\Client($sid, $token);
////        $client = new \Twilio\Rest\Client($apiKey, $apiSecret, $sid);
//        $client->account->messages->create(
//        // the number you'd like to send the message to
//            $phone,
//            array(
//                // A Twilio phone number you purchased at twilio.com/console
//                'from' => '+14242851861',
//                // the body of the text message you'd like to send
//                'body' => $msg
//            )
//        );
//    }
}